package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //创建索引库
    public void createIndexAndMapping() {
        //创建索引映射
        elasticsearchTemplate.createIndex(SkuInfo.class);
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    //导入全部数据到索引库
    public void importAll() {
        //远程调用查询数据
        List<Sku> skuList = skuFeign.findByspuId("all");
        if (skuList==null || skuList.size()<=0){
            throw new RuntimeException("当前商品无数据，无法导入索引库");
        }
        //先转json字符串再转skuinfo对象，达到对象转对象的效果
        String jsonString = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonString, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            //对skuInfo里面的一个属性进行修改,因为specmap是空的，所以自己转成map再添加进去
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);//如何将规格转换为map
            skuInfo.setSpecMap(map);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfoList);

    }

    //根据spuId远程调用feign查询skuList，然后添加到索引库
    public void importDataToESByspuId(String spuId) {
        //远程调用查询sku集合
        List<Sku> skuList = skuFeign.findByspuId(spuId);
        if (skuList==null|| skuList.size()<=0 ){
            throw new RuntimeException("当前商品数据不存在");
        }
        //将集合转换成json，再转成skuinfo
        String jsonString = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList = JSON.parseArray(jsonString, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfoList) {
            //将规格信息进行转换为map再填入specmap
            Map map = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(map);

        }
        //添加索引库
        esManagerMapper.saveAll(skuInfoList);
    }

    //根据spuId删除es索引库中相关sku数据
    public void delDataBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findByspuId(spuId);
        if (skuList==null|| skuList.size()<=0 ){
            throw new RuntimeException("当前商品数据不存在");
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
